import os
import json
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, Body
from pydantic import BaseModel
from datetime import datetime

from config.FileHandle import DOC_FOLDER_PATH

router = APIRouter(prefix="/api/UniversalDoc", tags=["UniversalDoc"])

# 确保doc目录存在
os.makedirs(DOC_FOLDER_PATH, exist_ok=True)

class ConfigItem(BaseModel):
    id: str
    name: str
    icon: str
    description: Optional[str] = None
    content: str
    htmlContent: Optional[str] = None
    compiledContent: Optional[str] = None
    createdDate: str
    updatedDate: Optional[str] = None
    agent_ids: Optional[List[str]] = None  # 关联的智能体ID列表
    params: Optional[Dict[str, Any]] = None  # 单独存储的参数
    type: Optional[str] = None  # 文档类型：quickTools, MCPTools, workflowComponents

@router.get("/list", response_model=List[ConfigItem])
async def get_config_list(type: Optional[str] = None):
    """获取配置文档列表，支持按类型过滤"""
    try:
        config_files = os.listdir(DOC_FOLDER_PATH)
        config_list = []
        
        for file_name in config_files:
            if file_name.endswith('.json'):
                with open(os.path.join(DOC_FOLDER_PATH, file_name), 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                    # 如果指定了类型，只返回匹配类型的配置
                    if type is None or config_data.get('type') == type:
                        config_list.append(config_data)
        
        return config_list
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/add", response_model=ConfigItem)
async def add_config(config: ConfigItem):
    """添加或更新配置文档"""
    try:
        # 确保配置包含必要的字段
        if not config.id or not config.name:
            raise HTTPException(status_code=400, detail="配置ID和名称不能为空")
            
        # 确保type字段是有效的
        if config.type and config.type not in ['quickTools', 'MCPTools', 'workflowComponents']:
            raise HTTPException(status_code=400, detail="无效的文档类型")
            
        # 保存配置到文件
        config_data = config.dict()
        config_data['createdDate'] = config_data['createdDate'] or datetime.now().isoformat()
        
        with open(os.path.join(DOC_FOLDER_PATH, f"{config.id}.json"), 'w', encoding='utf-8') as f:
            json.dump(config_data, f, ensure_ascii=False, indent=2)
            
        return config_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/delete")
def delete_config(config_id: str = Body(..., embed=True)):
    """删除配置文档"""
    try:
        file_path = os.path.join(DOC_FOLDER_PATH, f"{config_id}.json")
        if os.path.exists(file_path):
            os.remove(file_path)
            return {"success": True, "message": "配置已成功删除"}
        else:
            raise HTTPException(status_code=404, detail="找不到指定的配置文件")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除配置失败: {str(e)}")
